package com.payment.ktb.activity.main1;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.activity.ProtocolActivity;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.StringUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/11.
 */
public class NocardOrderSubmitNobindActivity extends BaseActivity {


    private String name;
    private String cert;
    private String yxq;
    private String cvv2;
    private String phone;
    private String msgcode;


    private long totalTime = 122000;
    private long intervalTime = 1000;
    MyCountDownTimer countDownTimer;



    @BindView(R.id.tv_nocardordersubmitnobind_amount)
    TextView tv_nocardordersubmitnobind_amount;
    @BindView(R.id.tv_nocardordersubmitnobind_cardbank)
    TextView tv_nocardordersubmitnobind_cardbank;
    @BindView(R.id.tv_nocardordersubmitnobind_cardno)
    TextView tv_nocardordersubmitnobind_cardno;
    @BindView(R.id.cb_nocardordersubmitnobind_protocol)
    CheckBox cb_nocardordersubmitnobind_protocol;

    @BindView(R.id.et_nocardordersubmitnobind_name)
    EditText et_nocardordersubmitnobind_name;
    @BindView(R.id.et_nocardordersubmitnobind_cert)
    EditText et_nocardordersubmitnobind_cert;
    @BindView(R.id.et_nocardordersubmitnobind_yxq)
    EditText et_nocardordersubmitnobind_yxq;
    @BindView(R.id.et_nocardordersubmitnobind_cvv2)
    EditText et_nocardordersubmitnobind_cvv2;
    @BindView(R.id.et_nocardordersubmitnobind_phone)
    EditText et_nocardordersubmitnobind_phone;
    @BindView(R.id.et_nocardordersubmitnobind_msgcode)
    EditText et_nocardordersubmitnobind_msgcode;
    @BindView(R.id.btn_nocardordersubmitnobind_obtainmsgcode)
    Button btn_nocardordersubmitnobind_obtainmsgcode;
    @BindView(R.id.btn_nocardordersubmitnobind_confirmpayd)
    Button btn_nocardordersubmitnobind_confirmpayd;
    @BindView(R.id.btn_nocardordersubmitnobind_isSelfBankCard)
    Button btn_nocardordersubmitnobind_isSelfBankCard;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_nocardordersubmitnobind);
        ButterKnife.bind(this);
        initTitle("订单支付");
        tv_nocardordersubmitnobind_amount.setText("¥ " + ConstantsPay.amount + "元");
        tv_nocardordersubmitnobind_cardbank.setText(ConstantsPay.bankCardName);
        tv_nocardordersubmitnobind_cardno.setText("尾号" + ConstantsPay.bankNo.substring(ConstantsPay.bankNo.length()-4,ConstantsPay.bankNo.length()));

//        forTest();

    }

    private void forTest() {

        et_nocardordersubmitnobind_name.setText("斯亚东");
        et_nocardordersubmitnobind_cert.setText("511321198912046198");
        et_nocardordersubmitnobind_yxq.setText("0819");
        et_nocardordersubmitnobind_cvv2.setText("051");
        et_nocardordersubmitnobind_phone.setText("15228935891");

    }


    /**
     *
     */
    private void initData() {

        name = et_nocardordersubmitnobind_name.getText().toString().trim();
        if (et_nocardordersubmitnobind_cert.getText().toString() != null && et_nocardordersubmitnobind_cert.getText().toString().length() == 12) {
            cert = SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPCERT);
        } else {
            cert = et_nocardordersubmitnobind_cert.getText().toString().trim();
        }
        yxq = et_nocardordersubmitnobind_yxq.getText().toString().trim();
        cvv2 = et_nocardordersubmitnobind_cvv2.getText().toString().trim();
        phone = et_nocardordersubmitnobind_phone.getText().toString().trim();
        msgcode = et_nocardordersubmitnobind_msgcode.getText().toString().trim();
    }



    @OnClick({R.id.btn_nocardordersubmitnobind_obtainmsgcode,R.id.btn_nocardordersubmitnobind_confirmpayd,R.id.tv_nocardordersubmitnobind_protocol,R.id.btn_nocardordersubmitnobind_isSelfBankCard})
    public void clickEvent(View view) {

        switch (view.getId()) {



            //免费获取
            case R.id.btn_nocardordersubmitnobind_obtainmsgcode:
                initData();
                if (checkPassWithObtainMsg()) {
                    obtainMsgCode();
                }


                break;
            //确认支付
            case R.id.btn_nocardordersubmitnobind_confirmpayd:
                initData();
                if (checkPassWithPaySubmit()) {

                    if (!cb_nocardordersubmitnobind_protocol.isChecked()) {
                        ToastUtils.showToast("请先同意服务协议");
                    } else {
                        paySubmit();
                    }

                }
                break;


            //支付服务协议
            case R.id.tv_nocardordersubmitnobind_protocol:
                startActivity(ProtocolActivity.class);
                break;


            //本人卡自动填充姓名和身份证
            case R.id.btn_nocardordersubmitnobind_isSelfBankCard:
                et_nocardordersubmitnobind_name.setText( SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPACCOUNT));
                et_nocardordersubmitnobind_cert.setText(StringUtils.handelIDNO(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPCERT)));

                break;
        }


    }


    /**
     *
     */
    private boolean checkPassWithPaySubmit() {

        if (TextUtils.isEmpty(name)) {
            ToastUtils.showToast("请输入真实姓名");
            return false;
        }
        if (TextUtils.isEmpty(cert) || (cert.length() != 15 && cert.length() != 18 )) {
            ToastUtils.showToast("请输入正确的持卡人身份证");
            return false;
        }
        if (TextUtils.isEmpty(yxq)) {
            ToastUtils.showToast("请输入有效期");
            return false;
        }
        if (TextUtils.isEmpty(cvv2)) {
            ToastUtils.showToast("请输入cvv2");
            return false;
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast("请输入正确的手机号!");
            return false;
        }

        if (TextUtils.isEmpty(msgcode)) {
            ToastUtils.showToast("请输入正确的验证码");
            return false;
        }
        return true;


    }

    /**
     *
     */
    private boolean checkPassWithObtainMsg() {

        if (TextUtils.isEmpty(name)) {
            ToastUtils.showToast("请输入真实姓名");
            return false;
        }
        if (TextUtils.isEmpty(cert) || (cert.length() != 15 && cert.length() != 18 )) {
            ToastUtils.showToast("请输入正确的持卡人身份证");
            return false;
        }
        if (TextUtils.isEmpty(yxq)) {
            ToastUtils.showToast("请输入有效期");
            return false;
        }
        if (TextUtils.isEmpty(cvv2)) {
            ToastUtils.showToast("请输入cvv2");
            return false;
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast("请输入正确的手机号!");
            return false;
        }

        return true;

    }


    /**
     * 获取短信验证码的时候，显示倒计时
     */
    class MyCountDownTimer extends CountDownTimer {

        /**
         *
         * @param millisInFuture
         *            倒计时总时间
         * @param countDownInterval
         *            每隔多久触发onTick方法
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            btn_nocardordersubmitnobind_obtainmsgcode.setText("重新获取");
            btn_nocardordersubmitnobind_obtainmsgcode.setEnabled(true);
        }

        @Override
        public void onTick(long arg0) { // arg0 表示距离本级倒计时结束还有多长时间

            btn_nocardordersubmitnobind_obtainmsgcode.setText("重新获取" + "(" + ((arg0 / 1000) -1) + ")" );
            btn_nocardordersubmitnobind_obtainmsgcode.setEnabled(false);

        }

    }








    /**
     * 获取注册的短信验证码
     */
    private void obtainMsgCode() {
        countDownTimer = new MyCountDownTimer(totalTime,intervalTime);
        countDownTimer.start();
        progressDialogUtils.showProgress();

        //构造传输参数

        String orderNo = ConstantsPay.orderNo;
        String cardAccount = name;
        String cardCert = cert;
        String cardYxq = yxq;
        String cardCvv = cvv2;
        String cardPhone = phone;
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        String sign = Md5Utils.md5Hex(cardAccount + cardCert + cardCvv + cardPhone +cardYxq + orderNo +  SharedPreferencesUtils.getString(ConstantsUser.userKey));


        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("orderNo",orderNo);
        map.put("cardAccount",cardAccount);
        map.put("cardCert",cardCert);
        map.put("cardYxq",cardYxq);
        map.put("cardCvv",cardCvv);
        map.put("cardPhone",cardPhone);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.nocardOrderSmsState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.getString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ToastUtils.showToast("获取验证码成功！");
                        btn_nocardordersubmitnobind_confirmpayd.setEnabled(true);
                    } else {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.getString("msg"));
                        countDownTimer.cancel();
                        btn_nocardordersubmitnobind_obtainmsgcode.setEnabled(true);
                        btn_nocardordersubmitnobind_obtainmsgcode.setText("重新获取");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    countDownTimer.cancel();
                    btn_nocardordersubmitnobind_obtainmsgcode.setEnabled(true);
                    btn_nocardordersubmitnobind_obtainmsgcode.setText("重新获取");
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                countDownTimer.cancel();
                btn_nocardordersubmitnobind_obtainmsgcode.setEnabled(true);
                btn_nocardordersubmitnobind_obtainmsgcode.setText("重新获取");
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));

            }
        });


    }




    /**
     *
     */
    private void paySubmit() {


        progressDialogUtils.showProgress();

        //构造传输参数
        String orderNo = ConstantsPay.orderNo;
        String smsCode = msgcode;
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //MD5(orderNo+smsCode+KEY)
        String sign = Md5Utils.md5Hex(orderNo + smsCode + SharedPreferencesUtils.getString(ConstantsUser.userKey));



        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("orderNo",orderNo);
        map.put("smsCode",smsCode);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.nocardOrderPayState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {


                        ToastUtils.showToast("提交请求成功！");
                        startActivity(NocardOrderResultWaitActivity.class);



                    } else {
                        progressDialogUtils.dismissProgress();
                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });


    }



}
